package org.example.elasticsearch;

import org.example.elasticsearch.domain.ESDoc;
import org.example.utils.BeanUtil;
import org.example.utils.Func;
import org.example.utils.ReflectUtil;
import org.example.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

import java.util.Arrays;

/**
 * @author: sql
 * @date: 2024/6/7
 * @Description: ES 工具
 * @version: 1.0
 */
@Slf4j
public class ESUtil {

    /**
     * 索引必须通过这个方法获取
     *
     * @param esIndex
     * @return
     */
    public static String getIndexName(ESIndex esIndex) {
        return getIndexName(esIndex.getIndexName());
    }

    public static String getIndexName(String indexName) {
        String profile = SpringUtil.getActiveProfile();
        if (Arrays.asList("prod", "st").contains(profile)) {
            return indexName;
        }
        DataSourceProperties dataSourceProperties = SpringUtil.getBean(DataSourceProperties.class);
        String databaseName = Func.parseUrlDbName(dataSourceProperties.getUrl());
        return String.format("%s_%s", databaseName, indexName);
    }

    public static String getDocId(ESIndex esIndex, Object obj) {
        Object fieldValue = ReflectUtil.getFieldValue(obj, esIndex.getPkField());
        if (fieldValue == null) {
            return null;
        }
        return fieldValue.toString();
    }

    public static ESDoc convertToEsDoc(ESIndex esIndex, Object target) {
        ESDoc doc = null;
        if (target.getClass() != esIndex.getEsDocClass()) {
            doc = BeanUtil.copy(target, esIndex.getEsDocClass());
        } else {
            doc = (ESDoc)target;
        }
        return doc;
    }

}

